package com.example.sil_facebook_login;

import java.util.Arrays;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.TextView;

import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import com.facebook.widget.LoginButton.UserInfoChangedCallback;

public class MainActivity extends FragmentActivity {

	//Facebook
	private LoginButton loginBtn;
	private TextView fb_userName,fb_accesstoken,fb_userid;
	private UiLifecycleHelper uiHelper;
	private static final List<String> PERMISSIONS = Arrays.asList("public_profile", "user_friends", "email");

	//private static final List<String> PERMISSIONS = Arrays.asList("public_profile", "user_birthday", "user_photos", "user_location", "read_friendlists", "email");
	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		//Facebook login OK
		
		uiHelper = new UiLifecycleHelper(this, statusCallback);
		uiHelper.onCreate(savedInstanceState);

		setContentView(R.layout.main);
		fb_accesstoken = (TextView) findViewById(R.id.fb_access_token);
		fb_userid = (TextView) findViewById(R.id.fb_user_id);
		fb_userName = (TextView) findViewById(R.id.fb_user_name);

		loginBtn = (LoginButton) findViewById(R.id.fb_login_button);
		
		
//		loginBtn.setUserInfoChangedCallback(new UserInfoChangedCallback() {
//			@Override
//			public void onUserInfoFetched(GraphUser user) {
//				if (user != null) {
//					fb_userName.setText("Hello, " + user.getName());
//					fb_userid.setText("ON_Create\nUser id: "+user.getId()+
//       		   			 "\nuser Location: "+user.getLocation()+
//       		   			 //"\nuser Email: "+user.getProperty("email").toString()+
//       		   			 "\nuser JSON:"+user.getInnerJSONObject()+
//       		   			 "\nuser bd: "+user.getBirthday());
//				} else {
//					fb_userName.setText("You are not logged");
//					fb_userid.setText("0");
//				}
//			}
//		});
		
		
	}

	
	
	//OK
	private Session.StatusCallback statusCallback = new Session.StatusCallback() {
		@Override
		public void call(Session session, SessionState state, Exception exception) {
			if (state.isOpened()) {
				
				Log.d("FacebookSampleActivity", "Facebook session opened");
                // make request to the /me API
                Request.newMeRequest(session, new Request.GraphUserCallback() {
                	// callback after Graph API response with user
                            // object
                            @Override
                            public void onCompleted(GraphUser user, Response response) {
                                if (user != null) {
                                    TextView welcome = (TextView) findViewById(R.id.fb_user_name);
                                    welcome.setText("Hello " + user.getName() + "!");
                                }
                            }
                });
               
			} else if (state.isClosed()) {
				
				Log.d("FacebookSampleActivity", "Facebook session closed");
			}
		}
	};

	public boolean checkPermissions() {
		Session s = Session.getActiveSession();
		if (s != null) {
			String permessi ="";
			for(int i=0;i<PERMISSIONS.size();i++){
				permessi +="\n"+PERMISSIONS.get(i);
			}
			Log.d("FacebookSampleActivity", "on checkPermissions true "+
				  "\n tutti i permessi sono presenti? "+s.getPermissions().containsAll(PERMISSIONS)+
				  "\n sessione:"+s.toString()+
				  "\n tutti i permessi richiesti "+permessi);

			return s.getPermissions().containsAll(PERMISSIONS);
		
		} else {
			Log.d("FacebookSampleActivity", "on checkPermissions false");
			return false;
		}
	}

	public void requestPermissions() {
		Session s = Session.getActiveSession();
		if (s != null){
			//loginBtn.setReadPermissions("email");
	    	//Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(this, Arrays.asList("email"));
	    	//s.requestNewReadPermissions(newPermissionsRequest);
//			  Session.OpenRequest openRequest = new Session.OpenRequest(activity).setPermissions(permissions).
			Log.d("FacebookSampleActivity", "on requestPermissions");			
			s.requestNewPublishPermissions(new Session.NewPermissionsRequest(this, PERMISSIONS));
			
		}
	}

	
	//TO DO
	@Override
	public void onResume() {
		
		uiHelper.onResume();

		final Session session = Session.getActiveSession();
		if(session != null){

        	if (session.isOpened()) {
        		if(!checkPermissions() && !session.getPermissions().containsAll(PERMISSIONS))		
    				requestPermissions();
               //Toast.makeText(this, session.getAccessToken(), Toast.LENGTH_LONG).show();
        	   fb_accesstoken = (TextView) findViewById(R.id.fb_access_token);
               fb_accesstoken.setText("Access Token\n"+session.getAccessToken());
               Log.e("tokenid","----------------------" + session.getAccessToken() + "---------------------");
                                            
               Request request = Request.newMeRequest(session, new Request.GraphUserCallback() {
                   @Override
                   public void onCompleted(GraphUser user, Response response) {
                       // If the response is successful
                       if (session == Session.getActiveSession()) {
                           if (user != null) {

                               fb_userid = (TextView) findViewById(R.id.fb_user_id);
                               fb_userid.setText("ON_RESUME\n\nUser id: "+user.getId()+
                            		   				//"\nuser Location: "+user.getLocation()+
                            		   				//"\nuser Email: "+user.getProperty("email").toString()+
                            		   				"\nuser JSON:"+user.getInnerJSONObject()+
                            		   				"\nuser bd: "+user.getBirthday());
                               
                               System.out.println("http://www.stopilike.it:8080/api/sil_log_sil/log_fb?aT="+session.getAccessToken()+"&uid="+user.getId());
                               
                           }   
                       }   
                   }   
               });
               Request.executeBatchAsync(request);             
           }
        }
  
       super.onResume();
	}

	@Override
	public void onPause() {
		super.onPause();
		uiHelper.onPause();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		uiHelper.onDestroy();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		uiHelper.onActivityResult(requestCode, resultCode, data);
		Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
	}

	@Override
	public void onSaveInstanceState(Bundle savedState) {
		super.onSaveInstanceState(savedState);
		uiHelper.onSaveInstanceState(savedState);
	}
	
	private static Session openActiveSession(Activity activity, boolean allowLoginUI, Session.StatusCallback callback, List<String> permissions) {
	    Session.OpenRequest openRequest = new Session.OpenRequest(activity).setPermissions(permissions);
	    		openRequest.setCallback(null);
	    Session session = new Session.Builder(activity).build();
	    if (SessionState.CREATED_TOKEN_LOADED.equals(session.getState()) || allowLoginUI) {
	        Session.setActiveSession(session);
	        session.openForRead(openRequest);
	        return session;
	    }
	    return null;
	}
	
	
	private static Session openActiveSession2(Activity activity, boolean allowLoginUI, Session.StatusCallback callback, List<String> permissions) {
	    Session.OpenRequest openRequest = new Session.OpenRequest(activity).setPermissions(permissions).setCallback(callback);
	    Session session = new Session.Builder(activity).build();
	    if (SessionState.CREATED_TOKEN_LOADED.equals(session.getState()) || allowLoginUI) {
	        Session.setActiveSession(session);
	        session.openForRead(openRequest);
	        return session;
	    }
	    return null;
	}
	
	
	
	
	
	
	
}
